﻿using Password_Manager.Database;
using Password_Manager.EncryptedFile;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Password_Manager
{
    public partial class ManagerInterface : Form
    {
        private int account; // 用户ID
        Generated generated = new Generated(); // 实例化密码生成器
        CreateDatabaseAndTables create = new CreateDatabaseAndTables();

        SimpleXmlHelper simple = new SimpleXmlHelper(); // 实例化XML操作类

        public ManagerInterface(int ID)
        {
            InitializeComponent();
            numericUpDown1.Visible = false;
            toolTip1.AutoPopDelay = 5000; // 提示显示时长（毫秒）
            toolTip1.InitialDelay = 10; // 鼠标悬停后延迟显示（毫秒）
            toolTip1.SetToolTip(textBox1, "无需输入，点击下面加密自动生成");
            toolTip1.SetToolTip(button7, "勾选下方选项框，选择生成的密码类型");
            account = ID; // 设置用户ID
        }

        private void button4_Click(object sender, EventArgs e) // 退出
        {
            this.Close();
            this.Dispose();
            // 退出应用程序
            Application.Exit();
        }

        private void ManagerInterface_Load(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            OperationRecord operation = new OperationRecord(account);
            operation.ShowDialog(); // 显示操作记录窗口
        }

        private void textBox2_TextChanged(object sender, EventArgs e) //原始密码输入框
        {

        }
        private void button7_Click(object sender, EventArgs e)// 自动生成密码按钮
        {
            int length = 16; // 默认密码长度

            string txt = ""; //默认是数字混合字母形式的密码

            if(checkCustom.Checked == true)
            {
                length = (int)numericUpDown1.Value; // 自定义密码长度
            }

            if (checkDigital.Checked == true)
            {
                txt = generated.GenerateNumericPassword(length); // 生成纯数字密码
                txtResult.Text = txt;
                MessageBox.Show($"已生成纯数字密码！{txt}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (checkNumberLetter.Checked == true)
            {
                txt = generated.GenerateAlphanumericPassword(length);
                txtResult.Text = txt; 
                MessageBox.Show($"已生成数字混合字母形式的密码！{txt}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void button1_Click(object sender, EventArgs e) //重置
        {
            txtResult.Text = string.Empty; // 清空密码文本框
        }

        private void checkBox4_CheckedChanged_1(object sender, EventArgs e)
        {
            CheckBox checkBox = (CheckBox)sender;
          
            numericUpDown1.Visible = checkBox.Checked;
            //判断是否为当前自定义
            if (checkBox.Checked)
            {
                numericUpDown1.Focus();
            }
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {
            
        }

        private void checkNumberLetter_CheckedChanged(object sender, EventArgs e) //数字字母混合
        {
            if (checkNumberLetter.Checked == true)
            {
                checkDigital.Checked = false;
            }
        }

        private void checkDigital_CheckedChanged(object sender, EventArgs e) //纯数字
        {
            if (checkDigital.Checked == true)
            {
                checkNumberLetter.Checked = false;
            }
        }

        private void button6_Click(object sender, EventArgs e) //加密按钮 使用AES加密
        {
            if (txtResult.Text == "")
            {
                MessageBox.Show("密码未生成！");
                return;
            }
            AddFile(txtResult.Text);
        }

        public void AddFile(string txtResult)
        {
           
            string uniqueId = GenerateUniqueId(); // 生成唯一ID

            int Id = create.GetNextAccountId(); // 确保获取到下一个账号ID
            AESEncryption aES = new AESEncryption();
            string key = aES.GenerateKey(); // 生成密钥
            create.SavePassword(Id, account, key, uniqueId); // 保存到数据库
            byte[] encryptedData = aES.Encrypt(key, Encoding.UTF8.GetBytes(txtResult)); // 加密密码
            string encryptedBase64 = Convert.ToBase64String(encryptedData); // 转换为Base64字符串
            textBox1.Text = encryptedBase64; // 显示加密后的密码


            // 创建单个文件项（不是列表）
            FileItem newItem = new FileItem();
            newItem.Encryption = encryptedBase64;  // 设置加密文本
            newItem.IdentificationCode = uniqueId; // 设置标识码

            // 添加到XML
            simple.AddFile(newItem);

        }

        private void button2_Click(object sender, EventArgs e) //解码
        {

            if (txtResult.Text == "")
            {
                MessageBox.Show("密码未生成！");
                return;
            }
            Decoding(txtResult.Text);


        }

        public void Decoding(string txtResult)
        {
            AESEncryption aES = new AESEncryption();

            string LdentificationCode = simple.FindIdentificationCodeByEncryptedFile(txtResult);

            string key = create.GetSecretKey(account, LdentificationCode); // 从数据库获取密钥
            if (string.IsNullOrEmpty(key))
            {
                MessageBox.Show("未找到密钥，请先加密密码！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                byte[] encryptedData = Convert.FromBase64String(txtResult); // 从Base64字符串转换为字节数组
                byte[] decryptedData = aES.Decrypt(key, encryptedData); // 解密
                string decryptedPassword = Encoding.UTF8.GetString(decryptedData); // 转换为字符串
                textBox1.Text = decryptedPassword; // 显示解密后的密码
                MessageBox.Show($"解密成功！密码是：{decryptedPassword}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解密失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GenerateUniqueId()// 生成唯一ID
        {
            string timePart = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString("x"); 
            string machinePart = Environment.MachineName.GetHashCode().ToString("x"); 
            string randomPart = Guid.NewGuid().ToString("N").Substring(0, 6); 
            return $"{timePart}-{machinePart}-{randomPart}";
        }
    }
}
